<template>
  <div class="pf-flow-prop-properties" id="js-properties-panel-custom">
    <el-table :data="elementPropertyList" size="mini" max-height="240" border fit>
      <el-table-column label="序号" width="50px" type="index" />
      <el-table-column label="属性名" prop="name" min-width="100px" show-overflow-tooltip />
      <el-table-column label="属性值" prop="value" min-width="100px" show-overflow-tooltip />
      <el-table-column label="操作" width="90px">
        <template v-slot="{ row, $index }">
          <el-button size="mini" link type="primary" @click="openAttributesForm(row, $index)"
            >编辑</el-button
          >
          <el-divider direction="vertical" />
          <el-button
            size="mini"
            link
            type="primary"
            style="color: #ff4d4f"
            @click="removeAttributes(row, $index)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="element-drawer__button">
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="openAttributesForm(null, -1)"
        >添加属性</el-button
      >
    </div>

    <el-dialog
      v-model="propertyFormModelVisible"
      title="属性配置"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <pf-form :model="propertyForm" :config="propertyFormConfig" ref="propertiesFormRef"></pf-form>
      <template v-slot:footer>
        <el-button size="mini" @click="propertyFormModelVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveAttribute">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, nextTick, onMounted, ref, Ref, toRefs, watch } from 'vue';
import { buildPropertiesInfo } from '@/views/page-config/flow/custom-properties/form-data';
import { FormModel } from 'pf-component';
import { CamundaTaskName, modeler, TaskName } from '@/views/page-config/flow/flow-modeler';
import { ElMessageBox } from 'element-plus';

export default defineComponent({
  name: 'ElementProperties',
  props: ['id'],
  setup(props) {
    const id: Ref = toRefs(props).id;
    const elementPropertyList: Ref<any[]> = ref([]);
    const propertyForm: Ref = ref({});
    const propertiesFormRef: Ref = ref(null);
    const propertyFormConfig: Ref<FormModel> = ref(buildPropertiesInfo());
    const propertyFormModelVisible: Ref<boolean> = ref(false);

    let editingPropertyIndex = -1;
    const otherExtensionList: any[] = [];
    let bpmnElementProperties: any[] = [];
    let bpmnElementPropertyList: any[] = [];

    const saveAttribute = () => {
      const { name, value } = propertyForm.value;
      if (editingPropertyIndex !== -1) {
        modeler.updateActiveModdleProperties(bpmnElementPropertyList[editingPropertyIndex], {
          name,
          value
        });
      } else {
        // 新建属性字段
        const newPropertyObject = modeler
          .getModdle()
          .create(CamundaTaskName.property, { name, value });
        // 新建一个属性字段的保存列表
        const propertiesObject = modeler.getModdle().create(CamundaTaskName.properties, {
          values: bpmnElementPropertyList.concat([newPropertyObject])
        });
        modeler.updateActiveElementExtensions(otherExtensionList.concat([propertiesObject]));
      }
      propertyFormModelVisible.value = false;
      resetAttributesList();
    };
    const resetAttributesList = () => {
      otherExtensionList.splice(0, otherExtensionList.length); // 其他扩展配置
      bpmnElementProperties =
        modeler.getActiveElement().businessObject?.extensionElements?.values?.filter((ex: any) => {
          if (ex.$type !== CamundaTaskName.properties) {
            otherExtensionList.push(ex);
          }
          return ex.$type === CamundaTaskName.properties;
        }) ?? [];

      // 保存所有的 扩展属性字段
      bpmnElementPropertyList = bpmnElementProperties.reduce(
        (pre, current) => pre.concat(current.values),
        []
      );
      // 复制 显示
      elementPropertyList.value = JSON.parse(JSON.stringify(bpmnElementPropertyList ?? []));
    };
    const openAttributesForm = (attr: any, index: number) => {
      editingPropertyIndex = index;
      propertyForm.value = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
      propertyFormModelVisible.value = true;
      nextTick(() => {
        if (propertiesFormRef.value) propertiesFormRef.value.clearValidate();
      });
    };
    const removeAttributes = (attr: any, index: number) => {
      ElMessageBox.confirm('确认移除该属性吗？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消'
      })
        .then(() => {
          elementPropertyList.value.splice(index, 1);
          bpmnElementPropertyList.splice(index, 1);
          // 新建一个属性字段的保存列表
          const propertiesObject = modeler.getModdle().create(CamundaTaskName.properties, {
            values: bpmnElementPropertyList
          });
          modeler.updateActiveElementExtensions(otherExtensionList.concat([propertiesObject]));
          resetAttributesList();
        })
        .catch(() => console.info('操作取消'));
    };

    onMounted(() => {});
    watch(
      id,
      val => {
        val && val.length && resetAttributesList();
      },
      { immediate: true }
    );
    return {
      propertyFormModelVisible,
      propertyForm,
      propertiesFormRef,
      propertyFormConfig,
      elementPropertyList,
      saveAttribute,
      removeAttributes,
      openAttributesForm
    };
  }
});
</script>
<style scoped lang="scss">
.#{$prefix} {
}
</style>
